import 'package:flutter/material.dart';
import 'package:myfirstflutter/utils/common_text_style.dart';

/*
 * 图片 按钮
 */
class ImageButton extends StatefulWidget {
// 常规图片路径
  final String normalImageString;

  // 按下图片路径
  final String pressedlImageString;

  //按钮文本
  final String title;

  //按下回调
  final Function onPressed;

  //文本与图片之间的距离
  final double padding;
  

  ImageButton({
    Key key,
    @required this.onPressed,
    @required this.normalImageString,
    this.pressedlImageString,
    // this.pressedImage,
    // this.normalImage,
    this.title,
    this.padding,
  }) : super(key: key);

  @override
  _ImageButtonState createState() {
    return _ImageButtonState();
  }
}

class _ImageButtonState extends State<ImageButton> {
  var isPressed = false;
//常规状态
  Image normalImage;

  //按下状态
  Image pressedImage;
  @override
  Widget build(BuildContext context) {
    var itemW = 25.0;
    double padding = widget.padding == null ? 5 : widget.padding;
    normalImage =
        Image.asset(widget.normalImageString, width: itemW, height: itemW);
    if (widget.pressedlImageString != null) {
      pressedImage =
          Image.asset(widget.pressedlImageString, width: itemW, height: itemW);
    }
    return GestureDetector(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          (isPressed && pressedImage != null)
              ? pressedImage
              : normalImage, //不同状态显示不同的Image
          widget.title.isNotEmpty
              ? Padding(padding: EdgeInsets.fromLTRB(0, padding, 0, 0))
              : Container(),
          widget.title.isNotEmpty //文本是否为空
              ? Text(
                  widget.title,
                  style: itemTextStyle,
                )
              : Container(),
        ],
      ),
      onTap: widget.onPressed,
      onTapDown: (d) {
        //按下，更改状态
        setState(() {
          isPressed = true;
        });
      },
      onTapCancel: () {
        //取消，更改状态
        setState(() {
          isPressed = false;
        });
      },
      onTapUp: (d) {
        //抬起，更改按下状态
        setState(() {
          isPressed = false;
        });
      },
    );
  }
}
